#!/bin/bash

LOG_FILE="alpha.log"
PID_FILE="find_alpha.pid"
CONDA_ENV="alpha"  # 你的conda环境名称

start() {
    if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE"); then
        echo "find_alpha.py 已经在运行。"
    else
        echo "启动 find_alpha.py..."
        source ~/miniconda3/bin/activate $CONDA_ENV
        nohup python -u find_alpha.py > "$LOG_FILE" 2>&1 &
        echo $! > "$PID_FILE"
        echo "find_alpha.py 已启动，PID 为 $(cat "$PID_FILE")。"
        tail -n 500 -f "$LOG_FILE"
    fi
}

stop() {
    if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE"); then
        echo "停止 find_alpha.py..."
        kill -TERM $(cat "$PID_FILE") && rm -f "$PID_FILE"
        echo "find_alpha.py 已停止。"
    else
        echo "find_alpha.py 未在运行。"
    fi
}

restart() {
    stop
    start
}

view_log() {
    if [ -f "$LOG_FILE" ]; then
        tail -n 500 -f "$LOG_FILE"
    else
        echo "日志文件未找到。"
    fi
}

echo "请选择操作："
echo "1) 启动 find_alpha.py"
echo "2) 停止 find_alpha.py"
echo "3) 重启 find_alpha.py"
echo "4) 查看日志"

# 设置终端为立即读取单个字符模式
stty -echo -icanon time 0 min 0
read -n 1 choice
stty sane  # 恢复终端设置

case "$choice" in
    1)
        start
        ;;
    2)
        stop
        ;;
    3)
        restart
        ;;
    4)
        view_log
        ;;
    *)
        echo "无效的选择。"
        exit 1
        ;;
esac
